<template>
  <div class="login-container">
    <div class="btnRight">
      <div class="leftTitle" style="flex: 1; -webkit-app-region: drag">隧道人员管理系统</div>
      <el-button class="loginTtn" style="background-color: #ccc;" @click="minhandler">一</el-button>
      <el-button v-if="flag" class="loginTtn" style="background-color: #ccc;" @click="maxhandler">口</el-button>
      <el-button v-else class="loginTtn" style="background-color: #ccc;" @click="maxhandler">回</el-button>
      <el-button class="loginTtn" style="background-color: #ccc;" @click="close">X</el-button>
    </div>
    <div class="packingDiv">
      <div class="leftDiv"></div>
      <div class="rightDiv">
        <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form" autocomplete="on" label-position="left">
          <div class="title-container">
            <h3 class="title">隧道人员管理系统</h3>
          </div>

          <el-form-item prop="account">
            <span class="svg-container">
              <svg-icon icon-class="user" />
            </span>
            <el-input ref="username" v-model="loginForm.account" placeholder="请输入用户名" name="account" type="text" tabindex="1" autocomplete="on" />
          </el-form-item>

          <el-tooltip v-model="capsTooltip" content="Caps lock is On" placement="right" manual>
            <el-form-item prop="password">
              <span class="svg-container">
                <svg-icon icon-class="password" />
              </span>
              <el-input
                :key="passwordType"
                ref="password"
                v-model="loginForm.password"
                :type="passwordType"
                placeholder="请输入密码"
                name="password"
                tabindex="2"
                autocomplete="on"
                @keyup.native="checkCapslock"
                @blur="capsTooltip = false"
                @keyup.enter.native="handleLogin"
              />
              <span class="show-pwd" @click="showPwd">
                <svg-icon :icon-class="passwordType === 'password' ? 'eye' : 'eye-open'" />
              </span>
            </el-form-item>
          </el-tooltip>

          <el-form-item v-if="codeUrl" prop="validationCode">
            <span class="svg-container">
              <i class="el-icon-s-comment"></i>
            </span>
            <el-input v-model="loginForm.validationCode" placeholder="请输入验证码" name="validationCode" type="string" tabindex="3" autocomplete="on" />
          </el-form-item>
          <div v-if="codeUrl" class="codeUrl">
            <span>验证码：</span>
            <img v-if="codeUrl" :src="codeUrl" width="200" height="40" alt />
            <a @click="resetCodeHandler">&nbsp;&nbsp;刷新</a>
          </div>
          <el-button :loading="loading" type="primary" style="width:100%;margin-bottom:30px;" @click.native.prevent="handleLogin">登录</el-button>
        </el-form>
      </div>
    </div>
  </div>
</template>

<script>
  import { eleValidator } from '@/utils/tools'
  import { login, getValidationCode } from '@/api/api'
  import { Message } from 'element-ui'
  import { mapGetters } from 'vuex'
  import { customNavigationBar } from '@/api/api'
  export default {
    name: 'Login',
    data() {
      return {
        codeUrl: '',
        flag: true,
        loginForm: {
          account: 'admin',
          password: 'admin',
          validationCode: ''
        },
        loginRules: {
          account: [
            { required: true, trigger: 'blur', message: '请输入用户名' }
          ],
          password: [
            { required: true, trigger: 'blur', message: '请输入密码' }
          ],
          validationCode: [
            { required: true, trigger: 'blur', message: '请输入验证码' }
          ],
        },
        passwordType: 'password',
        capsTooltip: false,
        loading: false,
        showDialog: false,
        redirect: undefined,
        otherQuery: {},
        routeValue: []
      }
    },
    computed: {
      ...mapGetters([
        'routeList'
      ])
    },
    watch: {
      $route: {
        handler: function (route) {
          const query = route.query
          if (query) {
            this.redirect = query.redirect
            this.otherQuery = this.getOtherQuery(query)
          }
        },
        immediate: true
      }
    },
    async mounted() {
      if (this.loginForm.username === '') {
        this.$refs.username.focus()
      } else if (this.loginForm.password === '') {
        this.$refs.password.focus()
      }
    },
    methods: {
      // 获取设置的快捷入口
      async setData() {
        try {
          let obj = { pageIndex: 1 }
          // 查询
          let response = await customNavigationBar('post', obj, false)
          let ary = response.data.items
          let list = []
          if (ary.length > 0) {
            ary.forEach(item => {
              this.routeList.forEach((edit, index) => {
                if (Number(item.order) === index + 1) {
                  list.push({
                    title: edit.title,
                    value: item.url
                  })
                }
              })
            })
          }

          let quickList = JSON.parse(JSON.stringify(list))
          if (quickList.length === 0) {
            await this.$store.dispatch('user/quickMenu', [
              { title: 'options1', value: '' },
              { title: 'options2', value: '' },
              { title: 'options3', value: '' },
              { title: 'options4', value: '' },
              { title: 'options5', value: '' },
              { title: 'options6', value: '' },
              { title: 'options7', value: '' }
            ])
          } else {
            await this.$store.dispatch('user/quickMenu', quickList)
          }
        } catch (err) {
          let list = []
        }
      },
      // 刷新验证码
      async resetCodeHandler() {
        try {
          let data = await getValidationCode()
          if (data.data) {
            this.loading = false
            this.codeUrl = data.data
          }
        } catch (err) {
          this.$message.error('验证码查询失败！')
        }
      },
      minhandler() {
        try {
          var ipcRender = require('electron').ipcRenderer
          ipcRender.send('min', "执行关闭")
        }
        catch (e) {
          this.$message.error('操作失败！')
        }
      },
      maxhandler() {
        this.flag = !this.flag
        try {
          var ipcRender = require('electron').ipcRenderer
          ipcRender.send('max', "执行关闭")
        }
        catch (e) {
          this.$message.error('操作失败！')
        }
      },
      close() {
        try {
          var ipcRender = require('electron').ipcRenderer
          ipcRender.send('handelClose', "执行关闭")
        }
        catch (e) {
          this.$message.error('操作失败！')
        }
      },
      checkCapslock(e) {
        const { key } = e
        this.capsTooltip = key && key.length === 1 && (key >= 'A' && key <= 'Z')
      },
      showPwd() {
        if (this.passwordType === 'password') {
          this.passwordType = ''
        } else {
          this.passwordType = 'password'
        }
        this.$nextTick(() => {
          this.$refs.password.focus()
        })
      },
      handleLogin() {
        this.$refs.loginForm.validate(async valid => {
          if (valid) {
            this.loading = true
            try {
              let res = await login(this.loginForm)
              await this.$store.dispatch('user/login', res.data)
              this.setData()
              this.$router.push({ path: '/', query: this.otherQuery })
              this.loading = false
            } catch (err) {
              if (!err.response) {
                Message({
                  message: '登录失败！',
                  type: 'error',
                  duration: 5 * 1000
                })
                this.loading = false
                return
              }
              if (err.response.data.message === "ValidateionCodeError") {
                Message({
                  message: '验证码错误！',
                  type: 'error',
                  duration: 5 * 1000
                })
              } else if (err.response.data.code === 401) {
                Message({
                  message: '用户名或密码错误！',
                  type: 'error',
                  duration: 5 * 1000
                })
              } else {
                Message({
                  message: '用户名或密码错误！',
                  type: 'error',
                  duration: 5 * 1000
                })
              }
              getValidationCode().then(data => {
                if (data.data) {
                  this.loading = false
                  this.codeUrl = data.data
                }
              })
              this.loading = false
            }
          } else {
            return false
          }
        })
      },
      getOtherQuery(query) {
        return Object.keys(query).reduce((acc, cur) => {
          if (cur !== 'redirect') {
            acc[cur] = query[cur]
          }
          return acc
        }, {})
      }
    }
  }
</script>

<style lang="scss">
  /* 修复input 背景不协调 和光标变色 */
  /* Detail see https://github.com/PanJiaChen/vue-element-admin/pull/927 */

  $bg: #283443;
  $light_gray: #586aa6;
  $cursor: #fff;

  .codeUrl {
    margin-bottom: 20px;
    display: flex;
    align-items: center;
    color: #000;
  }

  @supports (-webkit-mask: none) and (not (cater-color: $cursor)) {
    .login-container .el-input input {
      color: $cursor;
    }
  }

  .btnRight {
    display: flex;
    justify-content: flex-end;
    background-color: #ccc;

    .leftTitle {
      padding-left: 20px;
      display: flex;
      align-items: center;
    }

    .loginTtn {
      border: none;
      margin: 0;
      color: #000;
      font-weight: bold;
      background-color: #ccc;
    }
  }

  /* reset element-ui css */
  .login-container {
    .el-input {
      display: inline-block;
      height: 47px;
      width: 85%;

      input {
        background: transparent;
        border: 0px;
        -webkit-appearance: none;
        border-radius: 0px;
        padding: 12px 5px 12px 15px;
        color: $light_gray;
        height: 47px;
        caret-color: #000;

        &:-webkit-autofill {
          box-shadow: 0 0 0px 1000px $bg inset !important;
          -webkit-text-fill-color: $cursor !important;
        }
      }
    }

    .el-form-item {
      border: 1px solid rgba(255, 255, 255, 0.1);
      background: rgba(0, 0, 0, 0.1);
      border-radius: 5px;
      color: #454545;
    }
  }
</style>

<style lang="scss" scoped>
  $bg: #2d3a4b;
  $dark_gray: #889aa4;
  $light_gray: #586aa6;

  .login-container {
    height: 100%;
    width: 100%;
    background-color: #fff;
    overflow: hidden;

    .packingDiv {
      display: flex;
      height: 100%;

      .leftDiv {
        flex: 3;
        height: 100%;
        background-image: url('../../assets/imgs/train.png');
        background-size: 100% 100%;
      }
      .rightDiv {
        flex: 2;
        width: 520px;
        height: 100%;
        .login-form {
          position: relative;
          width: 520px;
          max-width: 100%;
          height: 100%;
          padding: 160px 35px 0;
          margin: 0 auto;
          overflow: hidden;
          .el-button {
            background-color: #586aa6;
            border-color: #586aa6;
          }
        }
      }
    }

    .tips {
      font-size: 14px;
      color: #fff;
      margin-bottom: 10px;

      span {
        &:first-of-type {
          margin-right: 16px;
        }
      }
    }

    .svg-container {
      padding: 6px 5px 6px 15px;
      color: $dark_gray;
      vertical-align: middle;
      width: 30px;
      display: inline-block;
    }

    .title-container {
      position: relative;

      .title {
        font-size: 26px;
        // color: lime;
        color: $light_gray;
        margin: 0px auto 40px auto;
        text-align: center;
        font-weight: bold;
      }
    }

    .show-pwd {
      position: absolute;
      right: 10px;
      top: 7px;
      font-size: 16px;
      color: $dark_gray;
      cursor: pointer;
      user-select: none;
    }

    .thirdparty-button {
      position: absolute;
      right: 0;
      bottom: 6px;
    }

    @media only screen and (max-width: 470px) {
      .thirdparty-button {
        display: none;
      }
    }
  }
</style>
